package com.gsj.gateway.config;

import com.alibaba.fastjson.JSON;
import com.gsj.common.pojo.R;
import com.gsj.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: clms-132
 * @description: 登录过滤器
 * @author: 闫克起
 * @create: 2021-07-20 11:05
 **/
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Autowired
    private RsaKeyProperties properties;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //请求头是否携带token
        //2.判断请求路径是否为登录路径
        String path= request.getPath().toString();
        System.out.println(path);
        if(path.contains("login")){
            return  chain.filter(exchange);//放行
        }

        String token = request.getHeaders().getFirst("token");
        if(!StringUtils.isEmpty(token)){
            if(JwtUtils.getInfoFromToken(token,properties.getPublicKey())!=null){
                return  chain.filter(exchange);//放行
            }
        }

        //响应一个结果----请先登陆

        DataBuffer buffer = null;
        try {
            //fastJson
            byte[] datas = JSON.toJSONString(R.error().message("请先登录")).getBytes("utf-8");
            buffer = response.bufferFactory().wrap(datas);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response.writeWith(Mono.just(buffer));

    }


    @Override
    public int getOrder() {
        return 0;
    }
}